<template>
	<view>
		<cu-page-bg></cu-page-bg>
		<view class="cu-w-100">
			<cu-navbar title="首页" :placeholder="true" :leftIconColor="{color:backgroundStyle.color}"
				:titleStyle="{color:backgroundStyle.color}" :style="getBackgroundStyle"
				bgColor="rgb(255,255,255,0)"></cu-navbar>
			<view class="cu-w-100 cu-p-20 cu-border-box">
				<u-sticky offset-top="88">
					<view class="cu-w-100 cu-ovr-hdn" style="height: 200px;">
						<u-swiper :list="swiperList" height="200" keyName="image" showTitle circular
							indicator></u-swiper>
					</view>
				</u-sticky>

				<view v-if="allAccountBooks === undefined || allAccountBooks.length === 0" class="cu-w-100 cu-py-20">
					<cu-card>
						<view
							class="cu-w-100 cu-row cu-font-weight cu-text-light-muted cu-j-sb cu-a-center cu-font-big cu-py-20 cu-mb-20">
							<view class="cu-span24-12 cu-row">
								<view style="border-left: 10rpx solid #CCC; margin-right: 20rpx;"></view>
								我的账本
							</view>
							<view class="cu-span24-12 cu-font cu-row cu-j-end cu-a-center">
								显示备注：<u-switch v-model="closeRemark" @change="!closeRemark" size="20"></u-switch>
							</view>
						</view>
						<view class="cu-w-100 cu-pt-20">
							<u-empty mode="data" text="还没有账本,快来添加吧"></u-empty>
						</view>
					</cu-card>
				</view>

				<view v-else class="cu-w-100 cu-py-20 cu-text-white">
					<block v-for="(item,idx) in allAccountBooks" :key="idx">
						<cu-card :style="cardStyle1">
							<view v-if="idx === 0"
								class="cu-w-100 cu-row cu-font-weight cu-text-light-muted cu-j-sb cu-a-center cu-font-big cu-py-20 cu-mb-20">
								<view class="cu-span24-12 cu-row">
									<view style="border-left: 10rpx solid #CCC; margin-right: 20rpx;"></view>
									我的账本
								</view>
								<view class="cu-span24-12 cu-font cu-row cu-j-end cu-a-center">
									显示备注：<u-switch v-model="closeRemark" @change="!closeRemark" size="20"></u-switch>
								</view>
							</view>
							<cu-card :key="idx" :style="idx % 2 == 0 ? cardStyle2 : cardStyle">
								<view class="cu-w-100 cu-row cu-j-sb cu-py-10">
									<view class="cu-font-weight cu-text-info cu-pr-10">
										<u-tag :text="item.accountType % 2 == 0 ? '共享账本' : '个人账本'" plain size="mini"
											shape="circle"
											:type="item.accountType % 2 == 0 ? 'success' : 'primary'"></u-tag>
									</view>
									<view class="cu-font-weight cu-w-100 cu-flex-1 cu-j-start cu-ovr-hdn">
										{{item.accountBookName}}
									</view>
									<view @click="itemClick(idx)"><u-icon name="list-dot" color="#FFF"
											size="24"></u-icon>
									</view>
								</view>
								<view class="cu-w-100 cu-row cu-j-start cu-py-10 cu-a-center">
									<view class="cu-px-10 cu-font-weight cu-font-big">结余：</view>
									<view class="cu-font-weight cu-py-10">
										<u-count-to color="#FFF" fontSize="32" :startVal="0"
											:endVal="item.surplus | fmtAmount" :useEasing="false" :decimals="2"
											:duration="500" separator=","></u-count-to>
									</view>
								</view>
								<view class="cu-w-100 cu-row cu-j-sb">
									<view class="cu-span24-24 cu-row cu-j-start cu-py-10 cu-a-center">
										<view class="cu-px-10">丨 总收入：</view>
										<view class="cu-font-weight cu-px-10">
											<u-count-to color="#dd524d" :startVal="0" font-size="16"
												:endVal="item.totalRevenue | fmtAmount" :useEasing="false" :decimals="2"
												:duration="500" separator=","></u-count-to>
										</view>
									</view>
									
								</view>
								<view class="cu-w-100 cu-row cu-j-sb">
									<view class="cu-span24-24 cu-row cu-j-start cu-py-10 cu-a-center">
										<view class="cu-px-10">丨 总支出：</view>
										<view class="cu-font-weight cu-px-10">
											<u-count-to color="#8bc34a" :startVal="0" font-size="16"
												:endVal="item.totalEcpenditure | fmtAmount" :useEasing="false"
												:decimals="2" :duration="500" separator=","></u-count-to>
										</view>
									</view>
									
								</view>
							</cu-card>
							
							<view v-if="closeRemark && item.remarks" class="cu-w-100 cu-row cu-pt-20 cu-px-10 cu-j-start cu-a-center cu-text-light-muted">
								备注：{{item.remarks}}
							</view>
							
							<view class="cu-w-100 cu-row cu-pt-20 cu-px-10 cu-j-sb cu-a-center cu-text-light-muted">
								<view class="cu-span24-12 cu-row cu-j-start cu-py-10 cu-a-center">
									<view class="cu-px-10"><u-count-to color="#17a2b8" :startVal="0"
											font-size="16" :endVal="item.totalPersion" :useEasing="false"
											:duration="500" separator=","></u-count-to> 人记账</view>,
									共<view class="cu-px-10"> <u-count-to color="#17a2b8" :startVal="0"
											font-size="16" :endVal="item.totalCount" :useEasing="false"
											:duration="500" separator=","></u-count-to> 笔</view>
								</view>
							</view>
							<view class="cu-w-100 cu-row cu-pt-20 cu-px-10 cu-j-end cu-a-center cu-text-light-muted">
								<view>创建时间：<span class="cu-text-info">{{item.createTime | formatDate}}</span></view>
							</view>
						</cu-card>
					</block>
				</view>
				<view class="cu-w-100 cu-py-20">
					<view class="cu-w-100 cu-row  cu-j-center">
						<u-button shape="circle" text="添加账本" @click="insertAccountBookBtn()"
							color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
							:customStyle="{width:'100%'}"></u-button>
					</view>
				</view>
			</view>

			<u-popup :show="show" mode="left" @close="close" @open="open" :customStyle="{width:'150%'}">
				<view class="cu-pt-50 cu-mt-50">
					<view class="cu-font-weight cu-px-20">{{accountBook.accountBookName}}</view>
					<cu-card>
						<u-cell-group :border="false">
							<u-cell title="编辑" @click="vk.myfn.gotoPage('/pages/accountbook/update/index','navigate')">
								<cu-icon custom-prefix="iconfont" slot="icon" size="24" name="icon-bianji"></cu-icon>
							</u-cell>
							<u-cell title="成员管理" :border="false" @click="cyglBtn()">
								<cu-icon custom-prefix="iconfont" slot="icon" size="24"
									name="icon-gerenzhongxin_chengyuanguanli"></cu-icon>
								<view slot="right-icon"><u-icon name="arrow-right"></u-icon></view>
							</u-cell>
						</u-cell-group>
					</cu-card>
					<cu-card :style="cardStyle1">
						<u-cell-group :border="false">
							<u-cell title="流水" :border="false"
								@click="vk.myfn.gotoPage('/pages/accountbook/turnover/index','navigate')">
								<cu-icon custom-prefix="iconfont" slot="icon" size="24"
									name="icon-liushuimingxi"></cu-icon>
								<view slot="right-icon"><u-icon name="arrow-right"></u-icon></view>
							</u-cell>
							<u-cell title="图表" :border="false" >
								<cu-icon custom-prefix="iconfont" slot="icon" size="24"
									name="icon-caisetubiao"></cu-icon>
								<view slot="right-icon"><u-icon name="arrow-right"></u-icon></view>
							</u-cell>
							<u-cell title="导出" :border="false" >
								<cu-icon custom-prefix="iconfont" slot="icon" size="24" name="icon-daochu"></cu-icon>
								<view slot="right-icon"><u-icon name="arrow-right"></u-icon></view>
							</u-cell>
						</u-cell-group>
					</cu-card>
					<cu-card :style="cardStyle1">
						<u-cell-group :border="false">
							<u-cell title=" 删除" :border="false" @click="clickCardItem('delAccountBook')">
								<cu-icon slot="icon" size="24" custom-prefix="iconfont" name="icon-shanchu"></cu-icon>
							</u-cell>
						</u-cell-group>
					</cu-card>
				</view>
			</u-popup>

			<u-modal :show="showModal" @close="closeModal" @cancel="closeModal" @confirm="confirmModal" ref="uModal"
				:title="modal.title" :content='modal.content' :zoom="true" :showCancelButton="true"
				:closeOnClickOverlay="true"></u-modal>
		</view>
	</view>
</template>

<script>
	let vk = uni.vk;
	export default {
		props: {
			flowDataReload: {
				type: Number,
				default: 0
			},
		},
		computed: {
			getBackgroundStyle() {
				let style = {};
				style.background = "linear-gradient(45deg, " + this.main + ", " + this.secondary + ")";
				// 合并用户传递的背景色对象
				Object.assign(style, this.backgroundStyle);
				return style;
			}
		},
		watch: {
			flowDataReload: {
				immediate: true,
				async handler(n) {
					console.log("flowDataReload",n)
					// 关闭
					this.show = false
					this.showModal = false;
					this.allAccountBooks = vk.getVuex('$accountbook.allAccountBooks');
				}
			},
		},
		filters: {
			formatDate(value) {
				if (!value) return '';
				const date = new Date(value);
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: 'long',
					day: 'numeric',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				});
			},
			formatTime(value) {
				if (!value) return '';
				// 创建 Date 对象（假设时间戳是毫秒级，如果是秒级需先 *1000）
				if (typeof value === 'string') {
					value = Number(value)
				}
				const date = new Date(value);
				// 提取时间部分并补零
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				// const seconds = String(date.getSeconds()).padStart(2, '0');
				// 拼接格式
				return `${hours}:${minutes}`;
			},
			fmtAmount(value) {
				if (!value) return 0;
				let rtn = value / 100
				return rtn.toFixed(2);
			},
		},
		data() {
			return {
				main: vk.getVuex('$app.color.main'),
				secondary: vk.getVuex('$app.color.secondary'),
				buttonColor: "linear-gradient(to right, " + vk.getVuex('$app.color.main') + "," + vk.getVuex(
					'$app.color.secondary') + ")",
				backgroundStyle: {
					color: "#FFF"
				},
				cardStyle1: {
					"marginTop": "20rpx",
				},
				cardStyle: {
					"marginTop": "20rpx",
					"background": "url(/pages/accountbook/static/111.png)"
				},
				cardStyle2: {
					"marginTop": "20rpx",
					"background": "url(/pages/accountbook/static/222.png)"
				},
				swiperList: [{
						image: "/pages/accountbook/static/333.jpg",
						title: "事忙先记账，不记事后忘。",
					},
					{
						image: "/pages/accountbook/static/444.jpg",
						title: "记账不停歇，财富滚滚来。",
					},
					{
						image: "/pages/accountbook/static/555.jpg",
						title: "别笑他是牛马, 他忙的不只是春天, 是一年四季",
					},
				],
				allAccountBooks: vk.getVuex('$accountbook.allAccountBooks'),
				closeRemark: true,
				show: false,
				accountBook: undefined,
				showModal: false,
				modelType: "",
				modal: {
					title: '温馨提示',
					content: '确认删除么？'
				},
				selectIndex: undefined
			};
		},
		onLoad(options) {
			vk = uni.vk;
			this.init(options);
		},
		methods: {
			// 页面数据初始化函数
			init(options) {
				this.main = vk.getVuex('$app.color.main');
				this.secondary = vk.getVuex('$app.color.secondary');
			},
			// 新增账本
			insertAccountBookBtn() {
				this.$store.dispatch('$accountbook/clearSelectAccountBook');
				vk.navigateTo("/pages/accountbook/update/index");
			},
			itemClick(index) {
				this.show = true
				this.selectIndex = index
				this.initSelectAccountBook(index);
				vk.setVuex('$accountKeepData.selectAccountBookIndex', index);
			},
			// 设置选中账本
			initSelectAccountBook(index) {
				const accountBook = this.allAccountBooks[index]
				this.accountBook = accountBook
				this.$store.dispatch('$accountbook/selectAccountBook', {
					accountBook
				});
			},
			open() {},
			close() {
				this.show = false
				this.selectIndex = undefined
			},
			clickCardItem(type) {
				if (type && type === 'delAccountBook') {
					this.modelType = "delAccountBook";
					this.modal.content = "确认删除" + this.accountBook.accountBookName + "么？";
					this.showModal = true;
				}
			},
			closeModal() {
				this.showModal = false;
			},
			confirmModal() {
				if (this.modelType === "delAccountBook") {
					this.delAccountBook()
				}
			},
			// 删除账本
			async delAccountBook() {
				const that = this
				await vk.callFunction({
					url: 'client/accountbook/kh/delAccountBook',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						accountBook: that.accountBook
					},
					success: (res) => {
						// 重置账本数据，进行查询
						that.$store.dispatch('$accountbook/clearEnqrData');
						that.close();
						that.closeModal();
						that.enqrAllAccountBook();
					},
					fail: (err) => {
						const msg = "删除失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			cyglBtn() {
				if (this.accountBook && !(this.accountBook.accountType == "2" || this.accountBook.accountType == 2)) {
					vk.alert("当前账本非共享账本-请修改账本类型后尝试", "错误提示");
					return
				}
				vk.navigateTo("/pages/accountbook/member/index");
			},
			async enqrAllAccountBook() {
				let that = this
				const pagination = {
					"pageIndex": 1,
					"pageSize": 1000
				}
				await vk.callFunction({
					url: 'client/accountbook/kh/enqrAccountBook',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						pagination: pagination
					},
					success: async (res) => {
						await that.$store.dispatch('$accountbook/enqrAccountBook', {
							res
						});
						that.allAccountBooks= vk.getVuex('$accountbook.allAccountBooks');
					},
					fail: (err) => {
						const msg = "查询账本失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
		}
	};
</script>

<style lang="scss" scoped>

</style>